import { useEffect, useState } from 'react';
import { Input, Table, TreeSelect, Button, Modal, Form, DatePicker, Select } from 'antd';
import axios from 'axios';
import { DownOutlined } from '@ant-design/icons';
import type { TreeSelectProps, GetProps, TableProps, FormProps } from 'antd';
import { createStyles } from 'antd-style';
type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};
// 表单验证
const { Option } = Select;
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
// 搜索框
type SearchProps = GetProps<typeof Input.Search>;
const { Search } = Input;
const onSearch: SearchProps['onSearch'] = (value, _e, info) => console.log(info?.source, value);
// 公司
const treeData = [
  {
    value: '2',
    title: '新乡大喇叭网络有限公司',
  },
  {
    value: '3',
    title: '大喇叭华中软件研发中心',
  },
  {
    value: '1',
    title: 'admin',
  },
];
// 证书
const certificateData = [
  {
    value: '1',
    title: '高压电工证',
  },
  {
    value: '2',
    title: '低压电工证',
  },
  {
    value: '3',
    title: '身份证',
  },
  {
    value: '4',
    title: '毕业证',
  },
];
const useStyle = createStyles(({ css, token }) => {
  const { antCls } = token;
  return {
    customTable: css`
      ${antCls}-table {
        ${antCls}-table-container {
          ${antCls}-table-body,
          ${antCls}-table-content {
            scrollbar-width: thin;
            scrollbar-color: #eaeaea transparent;
            scrollbar-gutter: stable;
          }
        }
      }
    `,
  };
});
interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}
const columns: any = [
  {
    title: '',
    dataIndex: '',
    key: 'name',
    fixed: 'left',
    align: 'center',
    render: (name, key) => {
      <div>
        <input
          type="checkbox"
          value={name}
        />
      </div>
    }
  },
  {
    title: '姓名',
    width: 100,
    dataIndex: 'name',
    key: 'age',
    fixed: 'left',
    sorter: true,
    align: 'center',
    render: (text, record) => (
      <a onClick={() => handleEdit(record)}>
        {text}
      </a>
    ),
  },
  { title: '岗位工资', dataIndex: 'base_pay', align: 'center', key: '1', fixed: 'left', },
  { title: '岗位档级', dataIndex: 'grade_title', align: 'center', key: '1', fixed: 'left', },
  { title: '性别', dataIndex: 'sex', align: 'center', key: '2' },
  { title: '生日', dataIndex: 'birthday', align: 'center', key: '3' },
  { title: '手机号', dataIndex: 'tel', align: 'center', key: '4' },
  { title: '身份证号', dataIndex: 'idcard', align: 'center', key: '5' },
  { title: '项目名称', dataIndex: 'title', align: 'center', key: '6' },
  { title: '公司名称', dataIndex: 'account', align: 'center', key: '7' },
  { title: '政治面貌', dataIndex: 'political_status', align: 'center', key: '8' },
  { title: '籍贯', dataIndex: 'address', align: 'center', key: '9' },
  { title: '学历', dataIndex: 'record', align: 'center', key: '10' },
  { title: '创建时间', dataIndex: 'create_time', align: 'center', key: '11' },
  { title: '员工状态', align: 'center', render: (text: number) => (text === 1 ? '在岗' : '离职'), key: '12' },
  {
    title: '用工方式',
    align: 'center',
    render: (text: number) => {
      switch (text) {
        case 1:
          return '长期派遣';
        case 2:
          return '短期派遣';
        default:
          return '学员';
      }
    }, key: '13'
  },
  { title: '先合同到期时间', dataIndex: 'agreement_end', align: 'center', key: '14' },
  { title: '现合同期限', dataIndex: 'agreement_num', align: 'center', key: '15' },
  { title: '银行卡卡号', dataIndex: 'bank_card', align: 'center', key: '16' },
  { title: '工资卡开户行', dataIndex: 'bank', width: 150, align: 'center', key: '17' },
  {
    title: '操作',
    key: 'operation',
    fixed: 'right',
    width: 100,
    render: () => (
      <a>
        更多
        <DownOutlined />
      </a>
    ),
  },
];
const App: React.FC = () => {
  const [form] = Form.useForm();
  // 确认新增
  const confirm = () => {
    form.submit();  // 使用 form.submit() 来提交表单
  };
  const onPopupScroll: TreeSelectProps['onPopupScroll'] = (e) => {
    console.log('onPopupScroll', e);
  };
  const [data, setData] = useState<DataType[]>([]);
  const [bigDataTwo, setbigDataTwo] = useState<DataType[]>([]);

  const [gradeData, setGrade] = useState<DataType[]>([]); // 假设你有一个名为grade的状态
  //档级请求数据
  const [treeBigData, setTreeBigData] = useState<DataType[]>([]);
  const fetchAndTransformData = async () => {
    try {
      const res = await axios.post('/grade/index/index');
      setTreeBigData(res.data.list);//原本的平面数据
      const transformedData = getTrees(res.data.list.map(val => ({ ...val, value: val.id })));
      setGrade(transformedData);//转换为树形菜单的数据
    } catch (error) {
      console.error('Error fetching or transforming data:', error); // 在控制台打印错误信息
    }
  };
  // 调用异步函数来获取和转换数据
  useEffect(() => {
    fetchAndTransformData();
  }, []); // 空依赖数组确保useEffect只在组件挂载时运行一次
  // 假设的getTrees函数，用于将数据转换为树形结构
  const getTrees = (arr) => {
    let data = arr.filter((item) => {
      item.children = arr.filter((e) => e.pid === item.id); // 注意修正了比较逻辑
      return !item.pid; // 假设pid为null或undefined表示顶级节点
    });
    return data;
  };
  useEffect(() => {//页面总数据
    const requestData = async () => {
      try {
        const res = await axios.post('/user/index/index');
        console.log(res.data.data);
        setData(res.data.data); // 确保 res.data.data 是正确的数据类型
        setbigDataTwo(res.data.data); // 确保 res.data.data 是正确的数据类型
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };
    requestData();
  }, []); // 空依赖数组，确保只在组件挂载时运行一次
  const { styles } = useStyle();

  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');//复选框
  const rowSelection: TableProps<DataType>['rowSelection'] = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };
  const [currentPage, setCurrentPage] = useState(1); // 当前页码状态
  // 分页
  const handleTableChange = (pagination) => {
    setCurrentPage(pagination.current);
  };
  const [long_term, setLongGame] = useState([]); // 假设你有一个名为grade的状态
  // 长期派遣按钮事件
  function longlyButton() {
    setData(bigDataTwo.filter(item => item.layout === 1))
  }
  // 短期派遣
  function shortButton() {
    setData(bigDataTwo.filter(item => item.layout === 2))
  }
  // 学员
  function student() {
    setData(bigDataTwo.filter(item => item.layout === 3))
  }
  // 在岗
  function onGuard() {
    setData(bigDataTwo.filter(item => item.layout === 4))
  }
  // 离职
  function dimission() {
    setData(bigDataTwo.filter(item => item.layout === 5))
  }
  const [isDisabled, setIsDisabled] = useState(true); // 初始状态设为禁用

  const [valueData, setValueData] = useState('');//员工
  const [companyData, setCompany] = useState();//公司
  const [itemName, setitemName] = useState('');//项目
  const [chooseGrade, setChooseGrade] = useState();//档级
  const [certificate, setCertificate] = useState('');//证书
  // 重置
  function setTwo() {
    setData(bigDataTwo);
    setValueData('');
    setCompany();
    setValueData('');
    setChooseGrade();
    setCertificate();
    // form.resetFields();
  }
  // 证件码
  const [sex, setSex] = useState('');
  const [birthdate, setBirthdate] = useState('');
  const [idCard, setIdCard] = useState('');//证件号
  // 更新员工名称状态
  const handleSearchInput = (event) => {
    setValueData(event.target.value);
    table_filter({ name: event.target.value }); // 调用筛选函数，传递搜索值
  };
  // 更新公司状态
  const handleCompanyChange = (newValue) => {
    console.log(newValue);
    setCompany(newValue);
    table_filter({ value: newValue }); // 调用筛选函数，只传递公司ID
  };
  // 更新项目名称状态
  const handleitemNameInput = (event) => {
    setitemName(event.target.value);
    table_filter({ title: event.target.value }); // 调用筛选函数，传递项目名称
  };
  // 更新档级状态
  const personnel_grade = (newValue) => {
    console.log(newValue);
    setChooseGrade(newValue);
    table_filter({ gradeid: newValue }); // 调用筛选函数，传递档级ID
  };
  // 更新证书状态
  const handleCertificateChange = (newValue) => {
    console.log(newValue);
    setCertificate(newValue);
    table_filter({ certid: newValue }); // 调用筛选函数，传递证书ID
  };
  function table_filter(conditions) {
    let filterdata = bigDataTwo.filter(item => {
      return (
        (!conditions.name || item.name.includes(conditions.name)) &&
        (!conditions.value || item.companyid === conditions.value) &&
        (!conditions.title || item.title.includes(conditions.title)) &&
        (!conditions.gradeid || item.gradeid === (conditions.gradeid)) &&
        (!conditions.certid || item.certid.includes(conditions.certid))
      );
    });
    setData(filterdata); // 更新数据状态（注意：您需要确保 setData 是正确定义的）
    console.log(filterdata);
  }
  // 新增的状态
  const [open, setOpen] = useState(false);
  const [formattedDateStart, setFormattedDateStart] = useState('');
  // 点击请求新增接口
  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    // console.log(birthday);
    console.log('表单提交的数据:', values);
    axios({
      method: 'post',
      url: '/user/index/add',
      data: {
        name: values.username,
        tel: values.tel,
        idcard: values.idcard,
        sex: sex,
        birthday: formattedDateStart,
        address: values.native,
        base_pay: values.backGround,
        gradeid: values.postMoney,
        record: values.study,
        bank: values.deposit,
        bank_card: values.bankCard,
        political_status: values.Political,
        companyid: values.company,
        projectid: values.company,
        layout: values.use,
        status: values.state,
        agreement_end: values.timeEnd,
        agreement_num: values.time,
        leave_time: values.timeEnd,
        entry_time: values.time,
      },
    }).then((res) => {
      console.log(res);
      // if (res.code == 1) {
      //   console.log('添加成功');
      // } else {
      //   console.log('添加失败');
      // }
    });
  }
  // 身份证号解析
  // 通过身份证获取生日以及性别; // 处理身份证号
  function getAgeSexAndBirthdate(idCard: string): { sex: '男' | '女' | null; birthdate: Date | null } {
    if (idCard.length !== 18) {
      console.error('身份证号码必须是18位。');
      return { sex: null, birthdate: null };
    }
    // 提取出生年月日
    const year = parseInt(idCard.substring(6, 10));
    const month = parseInt(idCard.substring(10, 12));
    const day = parseInt(idCard.substring(12, 14));
    const birthDate = new Date(year, month - 1, day); // 注意月份是从0开始的
    // 判断性别
    const sex = parseInt(idCard.charAt(16)) % 2 === 0 ? '女' : '男';
    return { sex, birthdate: birthDate };
  }
  // 身份证输入框事件处理函数
  function handleIdCardChange(e) {
    const newIdCard = e.target.value;
    const { sex: newSex, birthdate: newBirthdate } = getAgeSexAndBirthdate(newIdCard);
    if (newBirthdate != null) {
      const dateStart = newBirthdate;
      const birthdayHappy = `${dateStart.getFullYear()}-${String(dateStart.getMonth() + 1).padStart(2, '0')}-${String(dateStart.getDate()).padStart(2, '0')}`;
      setFormattedDateStart(birthdayHappy);//生日输入框赋值
      console.log(newSex, formattedDateStart);
      setSex(newSex || '');
      setBirthdate(formattedDateStart || '');
    }
  }
  //将树形菜单结构转换为平面数据
  function flattenTree(tree: any) {
    let result = [];
    function traverse(node: any) {
      result.push({ ...node, children: undefined }); // 复制节点并移除children属性  
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => traverse(child)); // 递归遍历子节点  
      }
    }
    tree.forEach(rootNode => traverse(rootNode)); // 遍历树的根节点  
    return result;
  }
  const [postMoney, setPostMoney] = useState('');//岗位工资
  // 档级填充工资
  const localStage = (e) => {
    console.log(treeBigData);
    const flattenedData = flattenTree(treeBigData);
    console.log(e);//打印出来当前选项的id
    let obj = flattenedData.find(item => item.id == e);
    console.log(obj);
    if (obj) {
      console.log(obj.money);
      setPostMoney(obj.money);
    } else {
      setPostMoney('');
    }
  }
  const [menuChild, setMenuChild] = useState([]);
  // 公司的change事件
  function companyInputChange(selectedNode) {
    console.log(selectedNode);
    axios({//菜单管理列表
      url: '/organization/project/company',
      method: 'post',
      data: {
        id: selectedNode,
        projectid: ''
      }
    }).then(res => {
      setMenuChild(res.data.list);//公司请求成功后，将当前数据复制给项目选项
    })
  }
  // 新增按钮
  function newAdd() {
    setOpen(true);
    form.resetFields();
  }
  return (
    <div>
      
      <b style={{ fontSize: '20px', marginBottom: '20px', display: 'block' }}>员工管理</b>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '10px', width: '90%' }}>
        <div style={{ display: 'flex', justifyContent: 'space-around', width: '100%' }}>
          <Search placeholder="请输入员工姓名" value={valueData} onInput={handleSearchInput} style={{ width: 200 }} />
          <TreeSelect
            style={{ width: '210px' }}
            onChange={handleCompanyChange}
            value={companyData}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择公司"
            treeDefaultExpandAll
            treeData={treeData}
            onPopupScroll={onPopupScroll}
          />
          <Search placeholder="请输入项目名称" value={itemName} onInput={handleitemNameInput} style={{ width: 200 }} />
          <TreeSelect
            placeholder="请选择档级"
            treeData={gradeData}
            value={chooseGrade}
            style={{ width: '210px' }}
            onChange={personnel_grade}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          />
          <TreeSelect
            style={{ width: '210px' }}
            onChange={handleCertificateChange}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择证书"
            treeDefaultExpandAll
            treeData={certificateData}
            onPopupScroll={onPopupScroll}
          />
        </div>
        <Button onClick={newAdd} style={{ position: 'absolute', right: '30px' }} type="primary">新增</Button>
        
        {/* 弹窗 */}
        <Modal
          title="添加人员信息"
          centered
          open={open}
          onOk={confirm}
          onCancel={() => setOpen(false)}
          width={1100}
        >
          <Form
            {...layout}
            form={form}
            name="control-hooks"
            onFinish={onFinish}
          >
            <div style={{ display: 'flex', justifyContent: 'space-around', width: '100%', marginTop: '20px' }}>
              <Form.Item<FieldType>
                label="姓名"
                style={{ width: '30%' }}
                name="username"
                // required表示该字段为必填项
                rules={[{ required: true, message: '姓名不能为空!' }]}
              >
                <Input placeholder='请输入姓名' />
              </Form.Item>
              <Form.Item<FieldType>
                label="手机号"
                name="tel"
                style={{ width: '30%' }}
                rules={[{ required: true, message: '手机号不能为空!' }]}
              >
                <Input placeholder='请输入手机号' />
              </Form.Item>
              <Form.Item<FieldType>
                label="证件号码"
                name="idcard"
                style={{ width: '30%' }}
                value={idCard}
                onInput={handleIdCardChange}
                rules={[{ required: true, message: '证件号码不能为空!' }]}
              >
                <Input placeholder='请输入证件号码' />
              </Form.Item>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-around', width: '100%', marginTop: '20px' }}>
              <Form.Item<FieldType>
                label="性别"
                name="sex"
                value={sex !== null ? sex.toString() : ''} readOnly
                style={{ width: '30%' }}
              // rules={[{ required: true, message: '性别不能为空!' }]}
              >
                <div style={{ display: 'none' }}>{sex}</div>
                <Input disabled={isDisabled} value={sex !== null ? sex.toString() : ''} placeholder='输入身份证号自动填充' />
              </Form.Item>
              <Form.Item<FieldType>
                label="生日"
                name="birthday"
                value={birthdate}
                readOnly
                style={{ width: '30%' }}
              // rules={[{ required: true, message: '生日不能为空!' }]}
              >
                {/* onClick={() => setIsDisabled(!isDisabled)} */}
                <div style={{ display: 'none' }}>{birthdate}</div>
                <Input disabled={isDisabled} value={birthdate} placeholder="输入身份证号自动填充" />
              </Form.Item>
              <Form.Item<FieldType>
                label="籍贯"
                name="native"
                style={{ width: '30%' }}
                rules={[{ required: true, message: '籍贯不能为空!' }]}
              >
                <Input placeholder='请输入籍贯' />
              </Form.Item>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-around', width: '100%', marginTop: '20px' }}>
              <Form.Item<FieldType>
                label="岗位档级"
                name="backGround"
                style={{ width: '30%' }}
                rules={[{ required: true, message: '岗位档级不能为空!' }]}
              >
                <TreeSelect
                  placeholder="请选择"
                  treeData={gradeData}
                  onChange={localStage}
                />
              </Form.Item>
              <Form.Item<FieldType>
                label="岗位工资"
                name="postMoney"
                value={postMoney}
                style={{ width: '30%' }}
              // rules={[{ required: true, message: '岗位工资不能为空!' }]}
              >
                <div style={{ display: 'none' }}>{postMoney}</div>
                <Input disabled placeholder='选择档级后自动填充' value={postMoney} />
              </Form.Item>
              <Form.Item<FieldType>
                label="学历"
                name="study"
                style={{ width: '30%' }}
                rules={[{ required: true, message: '学历不能为空!' }]}
              >
                <Select
                  placeholder="请选择"
                  allowClear
                >
                  <Option value="1">初高中以下</Option>
                  <Option value="2">高中</Option>
                  <Option value="3">大专</Option>
                  <Option value="4">本科</Option>
                  <Option value="5">研究生</Option>
                  <Option value="6">博士</Option>
                </Select>
              </Form.Item>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-around', width: '100%', marginTop: '20px' }}>
              <Form.Item<FieldType>
                label="开户行"
                name="deposit"
                style={{ width: '30%' }}
                rules={[{ required: true, message: '开互行不能为空!' }]}
              >
                <Input placeholder='请输入开户行' />
              </Form.Item>
              <Form.Item<FieldType>
                label="银行卡号"
                name="bankCard"
                style={{ width: '30%' }}
                rules={[{ required: true, message: '银行卡号不能为空!' }]}
              >
                <Input placeholder='请输入银行卡号' />
              </Form.Item>
              <Form.Item<FieldType>
                label="政治面貌"
                name="Political"
                style={{ width: '30%' }}
                rules={[{ required: true, message: '政治面貌不能为空!' }]}
              >
                <Input placeholder='请选择' />
              </Form.Item>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-around', width: '100%', marginTop: '20px' }}>
              <Form.Item<FieldType>
                label="公司"
                name="company"
                style={{ width: '30%' }}
                rules={[{ required: true, message: '公司不能为空!' }]}
              >
                <Select
                  placeholder="请选择"
                  onChange={companyInputChange}
                  allowClear
                >
                  <Option value="3">新乡大喇叭网络有限公司</Option>
                  <Option value="2">大喇叭华中软件研发中心</Option>
                </Select>
              </Form.Item>
              <Form.Item<FieldType>
                label="项目"
                name="item"
                style={{ width: '30%' }}
                rules={[{ required: true, message: '项目不能为空!' }]}
              >
                <Select
                  placeholder="请选择"
                  allowClear
                >
                  {menuChild.map((item, index) => (
                    <Option value={item.id}>{item.title}</Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item<FieldType>
                label="用工形式"
                name="use"
                style={{ width: '30%' }}
                rules={[{ required: true, message: '用工形式不能为空!' }]}
              >
                <Select
                  placeholder="请选择"
                  allowClear
                >
                  <Option value="1">长期派遣</Option>
                  <Option value="2">短期派遣</Option>
                  <Option value="3">学员</Option>
                </Select>
              </Form.Item>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-around', width: '100%', marginTop: '20px' }}>
              <Form.Item<FieldType>
                label="员工状态"
                name="state"
                style={{ width: '30%' }}
                rules={[{ required: true, message: '员工状态不能为空!' }]}
              >
                <Select
                  placeholder="请选择"
                  allowClear
                >
                  <Option value="1">在岗</Option>
                  <Option value="2">离职</Option>
                </Select>
              </Form.Item>
              <Form.Item<FieldType>
                label="合同到期时间"
                name="timeEnd"
                style={{ width: '30%' }}
                rules={[{ required: true, message: '合同到期时间不能为空!' }]}
              >
                <DatePicker style={{ width: '100%' }} placeholder='请输入合同到期时间' />
              </Form.Item>
              <Form.Item<FieldType>
                label="现合同期限(年)"
                name="time"
                style={{ width: '30%' }}
                rules={[{ required: true, message: '现合同期限不能为空!' }]}
              >
                <Input placeholder='请输入合同期限' />
              </Form.Item>
            </div>
          </Form>
        </Modal>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-around', width: '80%', marginBottom: '10px' }}>
        <Button type="primary">导入员工</Button>
        <Button onClick={longlyButton}>长期派遣</Button>
        <Button onClick={shortButton}>短期派遣</Button>
        <Button onClick={student}>学员</Button>
        <Button onClick={onGuard}>在岗</Button>
        <Button onClick={dimission} type="primary" danger>离职</Button>
        <Button onClick={setTwo}>重置</Button>
        <Button type="primary" danger>批量删除</Button>
      </div>
      <Table<DataType>
        className={styles.customTable}
        rowSelection={{ type: selectionType, ...rowSelection }}
        pagination={{
          pageSize: 10, // 每页显示10条数据
          current: currentPage,   // 初始显示第一页（可选）
          onChange: handleTableChange, // 处理页码变化的回调
        }}
        columns={columns}
        dataSource={data}
        scroll={{ x: 'max-content' }}
      />
    </div>
    
  );
};

export default App;